#coding:utf-8
'''
Created on Aug 17, 2012

@author: join
'''
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
import datetime
import os
import random
import sys

import socket
from ConfigParser import ConfigParser
import time
import logging
from lottery_terminal.common.exceptions import NetUnreachableError
import re
import threading
LOG = logging.getLogger('terminal')

TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"

def die(message, *args):

    sys.exit(1)

def get_host_name():
    return socket.gethostname()

def utcnow():
    return datetime.datetime.utcnow()

def now():
    return datetime.datetime.now()

def abspath(s):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), s)


def generate_mac():
    mac = [0x12, 0x03, 0xfe, random.randint(0x00, 0x7f),
           random.randint(0x00, 0xff), random.randint(0x00, 0xff)]
    return ':'.join(map(lambda x: "%02x" % x, mac))


def last_octet(address):
    return int(address.split(".")[-1])


def isotime(at=None):
    if not at:
        at = datetime.datetime.utcnow()
    return at.strftime(TIME_FORMAT)


def format_datetime(s,fmt="%Y-%m-%d %H:%M:%S"):
    #return datetime.strptime(s,fmt)
    return datetime.datetime.strptime(s,fmt)

def load_lottery_conf():
    if os.path.exists("/etc/lottery/lottery.conf"):
        filename = "/etc/lottery/lottery.conf"
    else:
        filename = os.path.join(os.path.dirname(os.path.dirname(__file__)),'lottery.conf')
    c = ConfigParser()
    try:
        c.read(filename)
        return dict(c.items('default'))
    except Exception as e:
        LOG.exception('can not read config of service : %s'%e)
        pass


def convert_datetime_to_str(dt, fmt="%Y-%m-%d"):
    return dt.strftime(fmt)


def parse_isotime(timestr):
    return datetime.datetime.strptime(timestr, TIME_FORMAT)

def in_period(start,end):
    return start<=datetime.datetime.now()<=end

def render(func):
    def _render(req, *args, **argskeys):
        try:
            start = time.time() 
            LOG.info("+++++++ %s start:%s ++++++++" % (func,start))
            result = func(req, *args, **argskeys)
            LOG.info("+++++++ total time:%s +++++++++" %(time.time()-start))
        except Exception as e:
            LOG.exception('an exception occured,%s:'%e)
            err_msg = u'系统错误'
            if isinstance(e,NetUnreachableError):
                err_msg = u'网络异常'
#                template,values = '500.html',{'err_msg':u'网络不通.'}
#            else:
            template,values = '500.html',{'err_msg':err_msg}
            
            return render_to_response(template,values,context_instance=RequestContext(req))
            
        #if result is redirect,do not need wrap
        if isinstance(result,HttpResponseRedirect):
            return result
        if isinstance(result,HttpResponse):
            raise Exception('function must be return tuple or list,not a httpresponse')
        
        if isinstance(result,tuple) or isinstance(result,list):
            if len(result)>1:
                template,values = result
            else:
                template,values = result[0],{}
        else:
            template,values = result,{}
        return render_to_response(template,values,context_instance=RequestContext(req))
    return _render


def generate_batchid():
    '''生成批次号'''
    mutex = threading.Lock()
    mutex.acquire()
    batchid = str(time.time()).replace('.','')
    mutex.release()
    batchid = batchid[:12] if len(batchid)>=12 else batchid+'0'*(12-len(batchid))
    return batchid

def ajaxrender(func):
    def _render(req, *args, **argskeys):
        try:
            start = time.time()
            LOG.info("+++++++ %s start:%s ++++++++" % (func,start))
            result = func(req, *args, **argskeys)
            LOG.info("+++++++ total time:%s +++++++++" %(time.time()-start))
        except Exception as e:
            LOG.exception('an exception occured:%s' % e)
            result = u'系统内部错误', 500
            if isinstance(e, NetUnreachableError):
                result = u'网络异常，请联系公司', 500

            
        if isinstance(result,HttpResponse):
            raise Exception('function must be return tuple or list,not a httpresponse')
        
        if isinstance(result,int):
            msg,status = '',result
        elif isinstance(result,tuple) or isinstance(result,list):
            msg,status = result
        else:
            msg,status = result,200
        return HttpResponse(msg,status=status)
    return _render


def perm(items, n=None):
    "排列，返回迭代器"
    if n is None:
        n = len(items)
    for i in range(len(items)):
        v = items[i:i+1]
        if n == 1:
            yield v
        else:
            rest = items[:i] + items[i+1:]
            for p in perm(rest, n-1):
                yield v + p

def comb(items, n=None):
    "组合，返回迭代器"
    if n is None:
        n = len(items)
    for i in range(len(items)):
        v = items[i:i+1]
        if n == 1:
            yield v
        else:
            rest = items[i+1:]
            for c in comb(rest, n-1):
                yield v + c
                
def getMD5Str(original_str):
   
    '''对str进行MD5加密'''
    
    if not original_str:
        return ''
    
    import hashlib
    
    md5 = hashlib.md5()
    md5.update(original_str)
    md5Str = md5.hexdigest()
    
    return md5Str 

def convert_money_number(money):
    '''将钱转换成xxx,xxx这种格式的字符串'''
    money_f = re.compile(r'(?<=\d)(?=(\d\d\d)+(?!\d))')
    return money_f.sub(r',',money)
